package com.lawyer.controller;

import java.math.BigDecimal;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import javax.persistence.EntityManager;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lawyer.dynamic.Criteria;
import com.lawyer.dynamic.Restrictions;
import com.lawyer.entity.Config;
import com.lawyer.entity.Documents;
import com.lawyer.entity.Lawyer;
import com.lawyer.entity.MoneyFlows;
import com.lawyer.entity.User;
import com.lawyer.model.DocumentsReq;
import com.lawyer.model.Message;
import com.lawyer.model.MessageConstant;
import com.lawyer.repository.ConfigRepository;
import com.lawyer.repository.DocumentsRepository;
import com.lawyer.repository.LawyerRepository;
import com.lawyer.repository.MoneyFlowsRepository;
import com.lawyer.repository.UserRepository;

@RestController
@RequestMapping(value = "/taskHall")
@Api(tags = "任务大厅")
@SuppressWarnings("all")
public class TaskHallController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private DocumentsRepository documentsRepository;

	@Autowired
	private EntityManager entityManager;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private LawyerRepository lawyerRepository;

	@Autowired
	private ConfigRepository configRepository;

	@Autowired
	private MoneyFlowsRepository moneyFlowsRepository;

	@ApiOperation(httpMethod = "GET", value = "任务列表", notes = "任务列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "page", required = false, value = "第一页 page = 0", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "size", required = false, value = "分页条数", paramType = "query", dataType = "String") })
	@RequestMapping(value = "/queryPage", method = RequestMethod.GET)
	public HttpEntity<?> queryPage(DocumentsReq documentsReq, @PageableDefault(page = 0, direction = Sort.Direction.DESC) Pageable pageable) {
		Message msg = new Message();
		try {
			Sort sort = new Sort(Sort.Direction.ASC, "offerPrice");
			// DESC=从高到低,ASC=从低到高
			if ("DESC".equals(documentsReq.getOfferPrice())) {
				sort = new Sort(Sort.Direction.DESC, "offerPrice");
			} else {
				sort = new Sort(Sort.Direction.DESC, "createdDate");
			}
			Pageable pageRequest = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);

			Criteria<Documents> criteria = new Criteria<Documents>();

			// 区域
			if (StringUtils.isNotEmpty(documentsReq.getLocation())) {
				criteria.add(Restrictions.eq("location", documentsReq.getLocation(), true));
			}
			// 分类
			if (StringUtils.isNotEmpty(documentsReq.getCaseTypeId())) {
				criteria.add(Restrictions.eq("caseTypeId", documentsReq.getCaseTypeId(), true));
			}
			// 大分类
			if (StringUtils.isNotEmpty(documentsReq.getCaseTypeId())) {
				criteria.add(Restrictions.eq("caseTypeParentId", documentsReq.getCaseTypeParentId(), true));
			}

			// 委托方
			if (StringUtils.isNotEmpty(documentsReq.getEntrust())) {
				criteria.add(Restrictions.eq("entrust", documentsReq.getEntrust(), true));
			}

			// 关健字
			if (StringUtils.isNotEmpty(documentsReq.getKeyWord())) {

				criteria.add(Restrictions.like("introduce", "%" + documentsReq.getKeyWord() + "%", true));

			}

			// 查询出上门服务文书
			if (StringUtils.isNotEmpty(documentsReq.getLawyerId())) {
				Lawyer lawyer = lawyerRepository.findOne(documentsReq.getLawyerId());
				if (lawyer == null || !lawyer.getDoorPermissions()) {
					criteria.add(Restrictions.ne("documentsType", "上门服务", true));
				}

			} else {
				criteria.add(Restrictions.ne("documentsType", "上门服务", true));
			}

			criteria.add(Restrictions.eq("status", 0, true));

			criteria.add(Restrictions.eq("pay", true, true));

			Page<Documents> page = documentsRepository.findAll(criteria, pageRequest);
			for (Documents doc : page.getContent()) {
				User user = userRepository.findOne(doc.getUserId());
				if (user != null) {
					doc.setHeaderIco(user.getHeaderIco());
					doc.setNickName(user.getNickName());
				}
			}

			msg.setData(page);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "GET", value = "任务详情", notes = "任务详情")
	@RequestMapping(value = "/taskInfo", method = RequestMethod.GET)
	public HttpEntity<?> taskInfo(Long documentId) {
		Message msg = new Message();
		try {

			Documents doc = documentsRepository.findOne(documentId);
			User user = userRepository.findOne(doc.getUserId());
			if (user != null) {
				doc.setHeaderIco(user.getHeaderIco());
				doc.setNickName(user.getNickName());
			}

			msg.setData(doc);
		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "PUT", value = "接受任务", notes = "接受任务")
	@RequestMapping(value = "/acceptTask", method = RequestMethod.PUT)
	public HttpEntity<?> acceptTask(String lawyerId, Long documentId) {
		Message msg = new Message();
		try {
			if (StringUtils.isEmpty(lawyerId) || documentId == null) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("lawyerId，documentId都不能为空");
				return new ResponseEntity<>(msg, HttpStatus.OK);
			}

			Documents doc = documentsRepository.findOne(documentId);
			// 0=未被接受，1=进行中，2=核实中，3=已完成
			if (doc.getStatus() != 0) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("任务已被接受");
				return new ResponseEntity<>(msg, HttpStatus.OK);

			}

			Lawyer lawyer = lawyerRepository.findOne(lawyerId);

			// 律师是否认证,true=已认证,false=未认证
			if (lawyer.getCertification() != 2) {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("律师未认证,不能接受任务");
				return new ResponseEntity<>(msg, HttpStatus.OK);

			}

			if (lawyer != null) {
				doc.setAcceptLawyerId(lawyerId);
				doc.setStatus(1);
				documentsRepository.save(doc);
			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没有找到到律师");
			}

		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

	@ApiOperation(httpMethod = "PUT", value = "更新任务状态", notes = "status :0=未被接受，1=进行中，2=核实中，3=已完成")
	@RequestMapping(value = "/complete", method = RequestMethod.PUT)
	public HttpEntity<?> complete(Long documentId, Integer status) {
		Message msg = new Message();
		try {
			Documents doc = documentsRepository.findOne(documentId);

			// 0=未被接受，1=进行中，2=核实中，3=已完成
			if (StringUtils.isNotEmpty(doc.getAcceptLawyerId())) {
				doc.setStatus(status);
				documentsRepository.save(doc);

				String lawyerId = doc.getAcceptLawyerId();
				Lawyer lawyer = lawyerRepository.findOne(lawyerId);
				User user = userRepository.findOne(doc.getUserId());

				// 结算
				if (status == 3) {
					Config config = new Config();
					if ("上门服务".equals(doc.getDocumentsType())) {
						config = configRepository.findByName("DoorServce");
					} else {
						config = configRepository.findByName("DocumentsWrite");
					}

					// 律师费用分成比例
					Double rate = Double.valueOf(config.getValue());
					// 律师最终收益
					
					Double multiplyResult = doc.getOfferPrice() * rate;
					
					Double lawyerChangeMoney = new BigDecimal(multiplyResult).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
				
					lawyer.setBalance(lawyer.getBalance() + lawyerChangeMoney);
					lawyerRepository.save(lawyer);
					
					// 律师金钱变更记录
					MoneyFlows lawyerFlow = new MoneyFlows();
					lawyerFlow.setTypeFlow(2);
					lawyerFlow.setUserId(user.getId());
					lawyerFlow.setUserName(user.getNickName());
					lawyerFlow.setLawyerName(lawyer.getNickName());
					lawyerFlow.setLawyerId(lawyerId);
					lawyerFlow.setPhone(lawyer.getPhone());
					lawyerFlow.setUserType("2");
					lawyerFlow.setChangeMoney(lawyerChangeMoney);
					lawyerFlow.setDescription(doc.getDocumentsType());
					moneyFlowsRepository.save(lawyerFlow);

				}

			} else {
				msg.setCode(MessageConstant.FAILED_CODE);
				msg.setMessage("没找到接受任务的律师");
			}

		} catch (Exception e) {
			msg.setCode(MessageConstant.FAILED_CODE);
			msg.setMessage(MessageConstant.FAILED_MSG);
		}
		return new ResponseEntity<>(msg, HttpStatus.OK);
	}

}
